﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using Microsoft.Win32;
using System.Text;
using System.IO;

namespace WFPapp
{
    public partial class FormMain : Form
    {
        
        SerialPort Readport = new SerialPort();
        SerialPort sendP = new SerialPort();
        string str = "";
        bool open = false;
        public FormMain()
        {
            InitializeComponent();
            
        }

        /*
         自动扫码枪分路给两电脑的方法：
         1.从控制盒接多个口
         优点：
         ①不需要考虑其他电脑的状态，扫码枪直接分给每台电脑
         2.控制盒的通讯信息全部给主电脑，再串联给其他电脑
         优点：
         可以无限制串联
         缺点：
         主扫码枪也要用到转接串口
             */

            /*
             
             */
             


        // 2.设置延时


        // 3.发送给其他串口
        private void FormMain_Load(object sender, EventArgs e)
        {
            RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
            if (keyCom != null)
            {
                string[] sSubKeys = keyCom.GetValueNames();
                cmbPort.Items.Clear();
                sendPort.Items.Clear();
                foreach (string sName in sSubKeys)
                {
                    string sValue = (string)keyCom.GetValue(sName);
                    cmbPort.Items.Add(sValue);
                    sendPort.Items.Add(sValue);
                }
                if (System.IO.File.Exists("c:\\testtxt.txt"))
                {
                    string lines = File.ReadAllText("c:\\testtxt.txt");
                    string[] txt = lines.Split(',');
                    cmbPort.Text = txt[0];
                    sendPort.Text = txt[2];
                    delayBox.Text = txt[3];
                    cmbBaud.Text = txt[1];
                    this.open =  Convert.ToBoolean(txt[4]);
                    ThreadPool.QueueUserWorkItem(new WaitCallback(OpReadPort));
                }
                else if(cmbPort.Items.Count > 0)
                {
                    cmbPort.SelectedIndex = 0;
                    sendPort.SelectedIndex = 0;
                    delayBox.Text = "1";
                    cmbBaud.Text = "9600";
                }
            }
            
            
            
            
           // ThreadPool.QueueUserWorkItem(new WaitCallback(OpReadPort));
        }

        /// <summary>
        /// 读取串口数据
        /// </summary>
        private void OpReadPort(object a)
        {
            this.Invoke((EventHandler)(delegate
            {
                try
                {
                    bool isOP = Readport.IsOpen;
                    if (!isOP)
                    {
                        Readport.PortName = cmbPort.Text;//"COM2"; // 串口名
                        Readport.BaudRate = Convert.ToInt32(cmbBaud.Text, 10);//波特率
                        Readport.DataBits = 8;//数据位
                        Readport.DtrEnable = true;
                        Readport.NewLine = "\r";
                        Readport.Open();
                        cmbPort.Enabled = false;
                        cmbBaud.Enabled = false;
                        sendPort.Enabled = false;
                        delayBox.Enabled = false;
                        button1.Text = "关闭串口";
                        this.open = true;
                        sendP = new SerialPort(sendPort.Text, 9600, Parity.None, 8, StopBits.One);
                        sendP.Open();
                    }
                    else
                    {
                        Readport.Close();
                        sendP.Close();
                        cmbPort.Enabled = true;
                        cmbBaud.Enabled = true;
                        sendPort.Enabled = true;
                        delayBox.Enabled = true;
                        button1.Text = "打开串口";
                        this.open = false;
                    }
                    
                   Readport.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("连接错误提示\r\n" + ex);

                }
            }));
        }

        private void sp_DataReceived(object sender,SerialDataReceivedEventArgs e)
        {
            System.Threading.Thread.Sleep(10);
            this.Invoke((EventHandler)(delegate
            {
                int delayTime = Convert.ToInt16(delayBox.Text) * 1000;
                Thread.Sleep(delayTime);
                str = Readport.ReadExisting();
                sendP.WriteLine(str);
               // textBox1.Text += str;
            }));
            
        }
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //cmbPort.Text
            if (!open)
            {
                MessageBox.Show("请先打开串口");
                return;
            }
            
            Readport.WriteLine(textBox2.Text);
            textBox2.Text = "";
        }
        

        private void selectCom(object sender, EventArgs e)
        {
            //MessageBox.Show(cmbPort.Text);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(OpReadPort));
            registered(cmbPort.Text, Convert.ToInt32(cmbBaud.Text), sendPort.Text, Convert.ToInt16(delayBox.Text),this.open);
        }
        /// <summary>
        /// 向txt文件写入
        /// </summary>
        /// <param name="readPort">读取的COM口</param>
        /// <param name="BaudRate">COM口的波特率</param>
        /// <param name="sendPort">发送的COM口</param>
        /// <param name="delay">延时时间</param>
        public void registered(string readPort,int BaudRate,string sendPort,int delay,bool isopen)
        {            //判断是否已经有了这个文件
            if (!System.IO.File.Exists("c:\\testtxt.txt"))
            {
                //没有则创建这个文件
                FileStream fs1 = new FileStream("c:\\testtxt.txt", FileMode.Create, FileAccess.Write);//创建写入文件                //设置文件属性为隐藏
                System.IO.File.SetAttributes(@"c:\\testtxt.txt", FileAttributes.Hidden);
                StreamWriter sw = new StreamWriter(fs1);
                sw.WriteLine(readPort + "," + BaudRate + "," + sendPort + "," + delay + "," + isopen);//开始写入值
                sw.Close();
                fs1.Close();
            }
            else
            {
                FileStream fs = new FileStream("c:\\testtxt.txt", FileMode.Open, FileAccess.Write);
                System.IO.File.SetAttributes(@"c:\\testtxt.txt", FileAttributes.Hidden);
                StreamWriter sr = new StreamWriter(fs);
                sr.WriteLine(readPort + "," + BaudRate + "," + sendPort + "," + delay + "," + isopen);//开始写入值
                sr.Close();
                fs.Close();
            }

        }
    }
}
